﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Threading;
using AmazonGlacierGUI.Core;
using AmazonGlacierGUI.Core.Infrastructure;
using AmazonGlacierGUI.Core.Model;
using AmazonGlacierGUI.Core.Services;
using AmazonGlacierGUI.UI.ViewModels;
using AmazonGlacierGUI.UI.Views;
using Raven.Client.Embedded;

namespace AmazonGlacierGUI.UI
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App : Application
    {
        public App()
        {
            this.Startup += new StartupEventHandler(App_Startup);
        }

        private SplashScreen _splashScreen;

        private void App_Startup(object sender, StartupEventArgs e)
        {
            AppContext.Current = new AppContext();
            Dispatcher.BeginInvoke(new Action(() =>
            {
                _splashScreen = new SplashScreen();
                _splashScreen.Show();
            }));
            Task.Factory.StartNew(() => AppContext.Current.Init())
                .ContinueWith((t) =>
                {
                    Dispatcher.BeginInvoke(new Action(() =>
                    {
                        if (t.Exception != null)
                        {
                            MessageBox.Show("Cannot initialize " + AppUtility.GetExceptionMessage(t.Exception), Constants.AppTitle,
                                            MessageBoxButton.OK, MessageBoxImage.Error);
                            Shutdown();
                            return;
                        }
                        _splashScreen.Hide();
                        JobsVM = new JobsViewModel();
                        new JobsView(JobsVM).ShowDialog();
                        Shutdown();
                    }));
                });
        }

        public static JobsViewModel JobsVM { get; private set; }
    }
}